package uk.ac.lkl.lpp.model.xml;



import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import uk.ac.lkl.common.util.ds.NotifyingList;
import uk.ac.lkl.lpp.model.PedagogyPlanModel;

import uk.ac.lkl.lpp.model.xml.ModelElementProcessor;
import uk.ac.lkl.lpp.model.ldo.Topic;


public class TopicSetProcessor extends ModelElementProcessor {

    public TopicSetProcessor() {
        super("TopicSet");
    }


    public void convertDataToElements(PedagogyPlanModel plan,
                                      Document document,
                                      Element pedagogyPlanElement) {
        // should be done in base class
        Element topicSetElement = document.createElement("TopicSet");
        pedagogyPlanElement.appendChild(topicSetElement);

        NotifyingList<Topic> topics = (NotifyingList<Topic>) plan
                .getList(Topic.class);
        for (int i = 0; i < topics.size(); i++) {
            Topic topic = topics.get(i);
            Element topicElement = document.createElement("Topic");
            topicElement.setAttribute("index", Integer.toString(i));

            String title = topic.getTitle();
            topicElement.setAttribute("title", title);

            String description = topic.getDescription();
            topicElement.setTextContent(description);

            topicSetElement.appendChild(topicElement);
        }
    }


    public void convertElementToData(PedagogyPlanModel plan, Element element) {
        NotifyingList<Topic> topics = new NotifyingList<Topic>(Topic.class);
        NodeList topicNodes = element.getElementsByTagName("Topic");
        for (int i = 0; i < topicNodes.getLength(); i++) {
            Element topicElement = (Element) topicNodes.item(i);
            String title = topicElement.getAttribute("title");
            String description = topicElement.getTextContent();
            Topic topic = new Topic(title, description);
            topics.add(topic);
        }
        plan.addList(Topic.class, topics);
    }

}
